﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace My
{
    /// <summary>
    /// MyGridView 的摘要描述
    /// </summary>
    public class MyGridView : GridView
    {
        public MyGridView()
        {
            //
            // TODO: 在此加入建構函式的程式碼
            //
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (this.HeaderRow != null)
            {
                this.HeaderRow.TableSection = TableRowSection.TableHeader;
            }

            base.OnPreRender(e);

            base.OnPreRender(e);

            GridViewRow[] pagers = { TopPagerRow, BottomPagerRow };

            foreach (GridViewRow pager in pagers)
            {
                if (pager != null)
                {
                    if (EnableExportExcel)
                    {
                        ScriptManager.GetCurrent(Page).RegisterPostBackControl(pager.FindControl("ibtnExcel"));
                    }
                    else
                    {
                        pager.FindControl("ibtnExcel").Visible = false;
                    }

                    if (EnableExportODS)
                    {
                        ScriptManager.GetCurrent(Page).RegisterPostBackControl(pager.FindControl("ibtnODS"));
                    }
                    else
                    {
                        pager.FindControl("ibtnODS").Visible = false;
                    }
                }
            }
        }

        protected override void OnSorting(GridViewSortEventArgs e)
        {
            if (e.SortExpression == MySortExpression)
            {
                MySortDirection = SwitchSortDirection(MySortDirection);
            }
            else
            {
                MySortDirection = SortDirection.Ascending;
            }

            MySortExpression = e.SortExpression;

            e.SortDirection = MySortDirection;

            base.OnSorting(e);
        }

        public string MySortExpression
        {
            get
            {
                if (ViewState["MySortExpression"] == null) return "";
                return ViewState["MySortExpression"] as string;
            }

            set { ViewState["MySortExpression"] = value; }
        }

        public SortDirection MySortDirection
        {
            get
            {
                if (ViewState["MySortDirection"] == null) return SortDirection.Ascending;
                return (SortDirection)ViewState["MySortDirection"];
            }

            set { ViewState["MySortDirection"] = value; }
        }

        public string MySortDirectionSQL
        {
            get
            {
                if (MySortDirection == SortDirection.Ascending)
                {
                    return "ASC";
                }
                else
                {
                    return "DESC";
                }
            }
        }

        public string MySortExpressionSQL
        {
            get { return string.Format("{0} {1}", MySortExpression, MySortDirectionSQL); }
        }

        public static SortDirection SwitchSortDirection(SortDirection direction)
        {
            if (direction == SortDirection.Ascending)
            {
                return SortDirection.Descending;
            }
            else
            {
                return SortDirection.Ascending;
            }
        }

        protected override bool OnBubbleEvent(object source, EventArgs e)
        {
            GridViewCommandEventArgs e2 = e as GridViewCommandEventArgs;

            if (e2.CommandName == "PageSize")
            {
                if (e2.CommandArgument as string == "")
                {
                    PageSize = 100000;
                    //AllowPaging = false;
                }
                else
                {
                    AllowPaging = true;
                    PageSize = int.Parse(e2.CommandArgument as string);
                    PageIndex = 0;
                }

                e2 = new GridViewCommandEventArgs(e2.CommandSource, new CommandEventArgs("Page", "1"));
            }

            return base.OnBubbleEvent(source, e2);
        }

        protected override void OnRowCommand(GridViewCommandEventArgs e)
        {
            if (e.CommandName == "PageSize")
            { 
            }
            else if (e.CommandName == "ExportExcel")
            {
                Export("xls");
            }
            else if (e.CommandName == "ExportODS")
            {
                Export("ods");
            }

            base.OnRowCommand(e);
        }

        public void Export(string filetype)
        {
            StringWriter writer = new StringWriter();
            HtmlTextWriter writer2 = new HtmlTextWriter(writer);
            if (this.TopPagerRow != null)
            {
                this.TopPagerRow.Visible = false;
            }
            if (this.BottomPagerRow != null)
            {
                this.BottomPagerRow.Visible = false;
            }
            HtmlForm form = new HtmlForm();
            form.Controls.Add(this);
            this.ClearControls(this);
            this.RenderControl(writer2);
            if (filetype == "xls")
            {
                string str = "ExportedFile_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
                this.PageObjectReference.Response.Clear();
                this.PageObjectReference.Response.AddHeader("content-disposition", "attachment;filename=" + str);
                this.PageObjectReference.Response.Charset = "";
                //this.PageObjectReference.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                this.PageObjectReference.Response.ContentType = "application/vnd.xls";
            }
            else
            {
                string str2 = "ExportedFile_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".ods";
                this.PageObjectReference.Response.Clear();
                this.PageObjectReference.Response.AddHeader("content-disposition", "attachment;filename=" + str2);
                this.PageObjectReference.Response.Charset = "";
                //this.PageObjectReference.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                this.PageObjectReference.Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet";
            }
            this.PageObjectReference.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
            this.PageObjectReference.Response.Write(writer.ToString());
            this.PageObjectReference.Response.End();
        }

        private void ClearControls(Control control)
        {
            for (int i = control.Controls.Count - 1; i >= 0; i--)
            {
                this.ClearControls(control.Controls[i]);
            }

            if ((!(control is TableCell) && !(control is TableRow)) && !(control is Table))
            {
                LiteralControl child = new LiteralControl();

                bool add = false;
                if (control is ITextControl || control.GetType().GetProperty("Text") != null)
                {
                    //child.Text = (control as ITextControl).Text;
                    child.Text = control.GetType().GetProperty("Text").GetValue(control, null) as string;
                    add = true;
                }

                if (add)
                {
                    control.Parent.Controls.Add(child);
                }

                control.Parent.Controls.Remove(control);
            }
        }

        protected Page PageObjectReference
        {
            get { return HttpContext.Current.Handler as Page; }
        }

        public event EventHandler PageSizeChanging;

        public bool EnableExportExcel
        {
            get
            {
                if (ViewState["EnableExportExcel"] == null)
                {
                    return false;
                }

                return (bool)ViewState["EnableExportExcel"];
            }
            set
            {
                ViewState["EnableExportExcel"] = value;
            }
        }

        public bool EnableExportODS
        {
            get
            {
                if (ViewState["EnableExportODS"] == null)
                {
                    return false;
                }

                return (bool)ViewState["EnableExportODS"];
            }
            set
            {
                ViewState["EnableExportODS"] = value;
            }
        }
    }
}